/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { warn, assetManager, AssetManager, SpriteFrame, Asset, Texture2D, resources, __private } from 'cc';
import { asyncIO } from './async';

const TAG = 'lcc/core/asset.ts';

/**
 * @zh
 * 加载远程资源，一般是图片
 *
 * @param url - 资源路径
 */
export function loadRemote<T extends Asset>(url: string) {
    return new Promise<T>((resolve) => {
        asyncIO.inc();
        assetManager.loadRemote(url, (err: Error | null, data: T) => {
            asyncIO.dec();
            if (!err && data) {
                resolve(data);
            } else {
                warn(TAG, `not found remote asset : ${url}`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 加载远程精灵帧
 *
 * @param url - 精灵帧URL路径
 */
export async function loadRemoteSpriteFrame(url: string) {
    let asset = await loadRemote(url);
    if (asset) {
        let spriteFrame = new SpriteFrame();
        spriteFrame.texture = asset as Texture2D;
        return spriteFrame;
    }
}

/**
 * @zh
 * 加载资源包
 *
 * @param nameOrUrl - 包名或者URL路径
 */
export function loadBundle(
    nameOrUrl: string,
    options: __private._cocos_core_asset_manager_shared__IBundleOptions | null = null
) {
    return new Promise<AssetManager.Bundle>((resolve) => {
        asyncIO.inc();
        assetManager.loadBundle(nameOrUrl, options, (err, bundle) => {
            asyncIO.dec();
            if (!err && bundle) {
                resolve(bundle);
            } else {
                warn(TAG, `not found bundle : '${nameOrUrl}'`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 通过UUID加载资源
 *
 * @param uuid - UUID
 */
export function loadAssetByUUID<T extends Asset>(uuid: string) {
    return new Promise<T>((resolve) => {
        asyncIO.inc();
        assetManager.loadAny([uuid], (err, asset: T) => {
            asyncIO.dec();
            if (!err && asset) {
                resolve(asset);
            } else {
                warn(TAG, `not found asset : '${uuid}'`);
                resolve(null);
            }
        });
    });
}

/**
 * @zh
 * 加载资源
 *
 * @param path 资源路径
 * @param type 资源类型
 * @param bundleOrName - 包对象或者包名称
 */
export function loadAsset<T extends Asset>(
    path: string,
    type: __private._cocos_core_asset_manager_shared__AssetType<T>,
    bundleOrName: AssetManager.Bundle | string = resources
) {
    return new Promise<T>((resolve) => {
        let bundle = bundleOrName instanceof AssetManager.Bundle ? bundleOrName : assetManager.getBundle(bundleOrName);
        if (!bundle) {
            warn(TAG, `not found bundle '${bundleOrName}'`);
            resolve(null);
        }
        asyncIO.inc();
        bundle.load(path, type, (err, data) => {
            asyncIO.dec();
            if (!err && data) {
                resolve(data);
            } else {
                warn(TAG, `not found asset '${path}' in '${bundle.name}'`);
                resolve(null);
            }
        });
    });
}
